package yue.shen.android.demo.adapter;

import android.content.Context;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.Date;
import java.util.List;

public class RViewHelper<T> {

    private Context context;
    private SwipeRefreshLayout swipeRefresh;
    private SwipeRefreshHelper swipeRefreshHelper;
    private RecyclerView recyclerView;
    private RViewAdapter<T> adapter;
    private int startPageNumber = 1;
    private boolean isSupportPaging;
    private int currentPageNum;
    private SwipeRefreshHelper.SwipeRefreshListener listener;


    public RViewHelper(Builder<T> builder) {
        this.swipeRefresh = builder.create.createSwipeRefresh();
        this.recyclerView = builder.create.createRecycleView();
        this.adapter = builder.create.createRecycleViewAdapter();
        this.context = builder.create.context();
        this.isSupportPaging = builder.create.isSupportPaging();
        this.listener = builder.listener;

        this.currentPageNum = this.startPageNumber;
        if (swipeRefresh != null) {
            swipeRefreshHelper = SwipeRefreshHelper.createSwipeRefreshHelper(swipeRefresh);
        }

        init();
    }

    private void init() {
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        if (swipeRefreshHelper != null) {
            swipeRefreshHelper.setListener(() -> {
                if (swipeRefresh != null && swipeRefresh.isRefreshing()) {
                    swipeRefresh.setRefreshing(false);
                }
                if (listener != null) {
                    listener.onRefresh();
                }
            });
        }
    }

    public void notifyAdapterDataSetChanged(List<T> list) {
        if (currentPageNum == startPageNumber) {
            adapter.updateData(list);
        } else {
            adapter.addData(list);
        }
        recyclerView.setAdapter(adapter);

        if (isSupportPaging) {
            //TODO 分页功能
            System.out.println("尚未开发");
        }
    }

    public static class Builder<T> {

        private final RViewCreate<T> create;
        private final SwipeRefreshHelper.SwipeRefreshListener listener;

        public Builder(RViewCreate<T> create, SwipeRefreshHelper.SwipeRefreshListener listener) {
            this.create = create;
            this.listener = listener;
        }

        public RViewHelper<T> build() {
            return new RViewHelper<>(this);
        }
    }
}
